#include "connection_pool.h"
#include <Poco/Data/SessionPool.h>
#include <Poco/Exception.h>
#include <stdexcept>

using namespace servercom;

std::shared_ptr<ConnectionPool> ConnectionPool::create(
    const std::string& db_type,
    const std::string& connection_string,
    int initial_size,
    int max_size) {
    return std::shared_ptr<ConnectionPool>(
        new ConnectionPool(db_type, connection_string, initial_size, max_size));
}

ConnectionPool::ConnectionPool(const std::string& db_type,
                             const std::string& connection_string,
                             int initial_size,
                             int max_size)
    : active_count_(0) {
    try {
        pool_ = std::make_unique<Poco::Data::SessionPool>(
            db_type, connection_string, initial_size, max_size);
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Failed to create connection pool: " + e.displayText());
    }
}

Poco::Data::Session ConnectionPool::getConnection(int timeout_ms) {
    try {
        active_count_++;
        return pool_->get();
    } catch (const Poco::Exception& e) {
        active_count_--;
        throw std::runtime_error("Failed to get connection: " + e.displayText());
    }
}

int ConnectionPool::activeConnections() const {
    return active_count_.load();
}

int ConnectionPool::idleConnections() const {
    return pool_->available();
}

void ConnectionPool::resize(int new_size) {
    try {
        pool_->setCapacity(new_size);
    } catch (const Poco::Exception& e) {
        throw std::runtime_error("Failed to resize pool: " + e.displayText());
    }
}